<template>
  <div id="space-detail-page">
    <div class="space-container">
      <!-- 空间信息 -->
      <div class="space-header">
        <h2>{{ space.spaceName }}（{{ SPACE_TYPE_MAP[space.spaceType] }}）</h2>
        <div class="space-actions">
          <a-button
            type="primary"
            v-if="canUploadPicture"
            :href="`/add_picture?spaceId=${id}`"
            target="_blank"
            class="create-btn"
          >
            创建图片
          </a-button>
          <a-button
            type="primary"
            ghost
            :icon="h(TeamOutlined)"
            :href="`/spaceUserManage/${id}`"
            target="_blank"
          >
            成员管理
          </a-button>

          <a-button
            type="primary"
            :href="`/add_picture/text_to_image`"
            target="_blank"
            class="create-btn"
          >
            AI文字生成图片
          </a-button>
          <a-button
            type="primary"
            ghost
            :icon="h(BarChartOutlined)"
            :href="`/space_analyze?spaceId=${id}`"
            target="_blank"
          >
            空间分析
          </a-button>
          <a-button :icon="h(EditOutlined)" @click="doBatchEdit"> 批量编辑</a-button>
          <a-tooltip
            :title="`占用空间 ${formatSize(space.totalSize)} / ${formatSize(space.maxSize)}`"
          >
            <a-progress
              type="circle"
              :percent="((space.totalSize * 100) / space.maxSize).toFixed(1)"
              :size="50"
              :stroke-color="getProgressColor(space.totalSize, space.maxSize)"
            />
          </a-tooltip>
        </div>
      </div>

      <!-- 搜索表单 -->
      <PictureSearchForm :onSearch="onSearch" />

      <!-- 按颜色搜索 -->
      <a-form-item label="按颜色搜索" style="margin-top: 16px">
        <color-picker format="hex" @pureColorChange="onColorChange" />
      </a-form-item>

      <!-- 图片列表 -->
      <div class="picture-list-container">
        <!-- 图片列表 -->
        <PictureList
          :dataList="dataList"
          :loading="loading"
          :onReload="fetchData"
          showOp
          :canEdit="canEditPicture"
          :canDelete="canDeletePicture"
        />
      </div>

      <!-- 分页器 -->
      <div class="pagination-container">
        <a-pagination
          :current="searchParams.current"
          :page-size="searchParams.pageSize"
          :total="total"
          :show-size-changer="true"
          @change="onPageChange"
        />
      </div>
    </div>
    <BatchEditPictureModal
      ref="batchEditPictureModalRef"
      :spaceId="id"
      :pictureList="dataList"
      :onSuccess="onBatchEditPictureSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, h, onMounted, reactive, ref, watch } from 'vue'
import { getSpaceVoByIdUsingGet } from '@/api/spaceController.ts'
import { message } from 'ant-design-vue'
import {
  listPictureVoByPageUsingPost,
  searchPictureByColorUsingPost,
} from '@/api/pictureController.ts'
import { formatSize } from '@/utils'
import PictureList from '@/components/PictureList.vue'
import PictureSearchForm from '@/components/PictureSearchForm.vue'
import Vue3ColorPicker, { ColorPicker } from 'vue3-colorpicker'
import 'vue3-colorpicker/style.css'
import BatchEditPictureModal from '@/components/BatchEditPictureModal.vue'
import { EditOutlined, BarChartOutlined, TeamOutlined } from '@ant-design/icons-vue'
import "echarts";
import { SPACE_PERMISSION_ENUM, SPACE_TYPE_MAP } from '../constants/space.ts'

// 分享弹窗引用
const batchEditPictureModalRef = ref()

// 打开批量编辑弹窗
const doBatchEdit = () => {
  if (batchEditPictureModalRef.value) {
    batchEditPictureModalRef.value.openModal()
  }
}

// 批量编辑成功后，刷新数据
const onBatchEditPictureSuccess = () => {
  fetchData()
}

const props = defineProps<{ id: string | number }>()

const space = ref<API.SpaceVO>({})

// 获取空间详情
const fetchSpaceDetail = async () => {
  try {
    const res = await getSpaceVoByIdUsingGet({ id: props.id })
    if (res.data.code === 0 && res.data.data) {
      space.value = res.data.data
    } else {
      message.error('获取空间详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取空间详情失败：' + e.message)
  }
}

onMounted(() => {
  fetchSpaceDetail()
})

// 数据
const dataList = ref([])
const total = ref(0)
const loading = ref(true)

onMounted(() => {
  fetchData()
})

/**
 * 计算进度条颜色
 */
const getProgressColor = (used: number, max: number) => {
  const percent = (used / max) * 100
  if (percent < 50) return '#52c41a' // 绿色
  if (percent < 80) return '#faad14' // 黄色
  return '#f5222d' // 红色
}

// 搜索条件
const searchParams = ref<API.PictureQueryRequest>({
  current: 1,
  pageSize: 12,
  sortField: 'createTime',
  sortOrder: 'descend',
})

// 分页参数
const onPageChange = (page, pageSize) => {
  searchParams.value.current = page
  searchParams.value.pageSize = pageSize
  fetchData()
}

// 搜索
const onSearch = (newSearchParams: API.PictureQueryRequest) => {
  searchParams.value = {
    ...searchParams.value,
    ...newSearchParams,
    current: 1,
  }
  fetchData()
}

// 获取数据
const fetchData = async () => {
  loading.value = true
  // 转换搜索参数
  const params = {
    spaceId: props.id,
    ...searchParams.value,
  }
  const res = await listPictureVoByPageUsingPost(params)
  if (res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

const onColorChange = async (color: string) => {
  const res = await searchPictureByColorUsingPost({
    picColor: color,
    spaceId: props.id,
  })
  if (res.data.code === 0 && res.data.data) {
    const data = res.data.data ?? []
    dataList.value = data
    total.value = data.length
    console.log('更新后的 dataList:', dataList.value)
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
}

watch(
  () => props.id,
  (newSpaceId) => {
    fetchSpaceDetail()
    fetchData()
  },
)

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (space.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canManageSpaceUser = createPermissionChecker(SPACE_PERMISSION_ENUM.SPACE_USER_MANAGE)
const canUploadPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_UPLOAD)
const canEditPicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDeletePicture = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)


</script>

<style scoped>
/* 页面背景 */
#space-detail-page {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to right, #e3f2fd, #bbdefb, #90caf9);
  padding: 40px 0;
}

/* 容器 */
.space-container {
  width: 90%;
  max-width: 1200px;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

/* 头部布局 */
.space-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
}

/* 标题 */
.space-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

/* 按钮 + 进度条 */
.space-actions {
  display: flex;
  align-items: center;
  gap: 20px;
}

/* 按钮样式 */
.create-btn {
  background: linear-gradient(to right, #42a5f5, #1976d2);
  border: none;
  color: white;
  font-weight: bold;
  transition: all 0.3s ease;
}

.create-btn:hover {
  background: linear-gradient(to right, #64b5f6, #1e88e5);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

/* 图片列表容器 */
.picture-list-container {
  margin-top: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

/* 分页器 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* Ant Design 按钮优化 */
:deep(.ant-btn-primary) {
  background: linear-gradient(to right, #42a5f5, #1976d2);
  border: none;
  color: white;
}

:deep(.ant-btn-primary:hover) {
  background: linear-gradient(to right, #64b5f6, #1e88e5);
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
}

/* 进度条动画 */
:deep(.ant-progress-circle) {
  transition: all 0.3s ease-in-out;
}
</style>
